var express = require('express');
// 引入路径模块
var path = require('path');
// 打印日志
var logger = require('morgan');
// 引入验证token的中间件
const { verify } = require('./utils/token')
// 引入路由器
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
const systemRouter = require('./routes/system')
const medicineRouter = require('./routes/medicine')
const diseaseRouter = require('./routes/disease')
const articleRouter = require('./routes/article')
const expertRouter = require('./routes/expert')
const myuserRouter = require('./routes/myuser')
const officeRouter = require('./routes/office')
const hospitalRouter = require('./routes/hospital')
const adRouter = require('./routes/ad')
const orderRouter = require('./routes/order')
const recipelRouter = require('./routes/recipel')
const commentRouter = require('./routes/comment')
// 设置端口
process.env.PORT = 3001
// 创建WEB服务器
var app = express();

// 使用打印日志中间件
app.use(logger('dev'));
// 将post请求过程中格式为json的参数解析为对象
// {"a":"1", "b":"2"}   ->  {a: '1', 'b': 2}
app.use(express.json());
// 将post请求过程中格式为a=1&b=2的参数解析为对象 {a:'1',b:'2'}
app.use(express.urlencoded({ extended: false }));
// path.join()  将路径拼接为绝对路径
// 托管静态资源
app.use(express.static(path.join(__dirname, 'public')));

// 验证token
// app.use(verify())

// 挂载路由器
app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/system', systemRouter)
app.use('/medicine', medicineRouter)
app.use('/disease',diseaseRouter)
app.use('/article',articleRouter)
app.use('/expert',expertRouter)
app.use('/myuser',myuserRouter)
app.use('/office',officeRouter)
app.use('/hospital', hospitalRouter)
app.use('/ad',adRouter)
app.use('/order',orderRouter)
app.use('/recipel',recipelRouter)
app.use('/comment',commentRouter)

// 错误处理中间件，拦截所有路由中产生的错误
app.use(function(err, req, res, next) {
  console.log(err)
  // 如果是token问题，响应没有权限
  if(err.name == 'UnauthorizedError') {
    return res.send({
      code: 400,
      msg: '没有访问权限'
    })
  }
  res.send({
    code: 500,
    msg: '服务器端错误'
  })
});

// 将创建的WEB服务器暴露出来，作为一个模块被其它的模块使用
module.exports = app;
